package com.clkj.xiuzheng.service.shangcheng;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clkj.xiuzheng.dao.shangcheng.*;
import com.clkj.xiuzheng.pojo.common.*;
import com.clkj.xiuzheng.pojo.shangcheng.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mapping.model.PreferredConstructorDiscoverer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.*;

@Service
public class ScUserServiceImpl implements ScUserService{
    @Autowired
    private ScUserMapper scUserMapper;

    @Autowired
    ScAddressMapper scAddressMapper;

    @Autowired
    ScIdentityMapper scIdentityMapper;

    @Autowired
    ScIdentityinfoMapper scIdentityinfoMapper;

    @Autowired
    SCMenuMapper scMenuMapper;

    @Autowired
    ScCompanyMapper scCompanyMapper;

    @Autowired
    private UserCommDetailMapper detailsMapper;

    @Autowired
    private UserCommissionMapper commissionMapper;

    @Autowired
    private PromoterApplyMapper promoterApplyMapper;

    @Autowired
    private UserScoreMapper scoreMapper;

    @Autowired
    private PromoCodeMapper promoCodeMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    private Map map;


    @Override
    public void addAddress(Address address) {
        if(address.getAddressFlag()==1){
            Example example = new Example(Address.class);
            Example.Criteria criteria =example.createCriteria();
            criteria.andEqualTo("userId",address.getUserId());
            Address address1 = new Address();
            address1.setAddressFlag(0);
            scAddressMapper.updateByExampleSelective(address1,example);
        }
        if(address.getAddressId()!=null){
            scAddressMapper.updateByPrimaryKeySelective(address);
        }else{
            scAddressMapper.insertSelective(address);

        }


    }

    @Override
    public PageInfo getUserList(Integer companyId, Integer pageSize, Integer pageNum,String userName,String startTime,String endTime) {
        PageHelper.startPage(pageNum, pageSize);
        if(companyId==0){
            List<SUser> users = scUserMapper.getAllUserList(userName,startTime,endTime);
            return new PageInfo(users);
        }
        List<SUser> users = scUserMapper.getUserList(companyId,userName,startTime,endTime);
        return new PageInfo(users);
    }

    @Override
    public PageInfo getManagerList(Integer companyId, Integer pageSize, Integer pageNum, String userName, String startTime, String endTime) {
        PageHelper.startPage(pageNum, pageSize);
        List<SUser> users = scUserMapper.getManagerList(companyId,userName,startTime,endTime);
        return new PageInfo(users);
    }

    @Override
    public void addIdentity(Identity identity) {
        if (identity.getIdentityId()==null){
            scIdentityMapper.addIdentity(identity);
        }
         for (IdentityInfo identityInfo : identity.getList()){
             identityInfo.setIdentityId(identity.getIdentityId());
         }
        scIdentityinfoMapper.insertList(identity.getList());
    }

    @Override
    public Map userLogin(String code,Integer companyId,Integer parentId,Integer shareId) {
        map = new HashMap();
        String accessToken = "";
        String unionid = "";
        String urls = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + WxApi.getMiniAppId()
                + "&secret="
                + WxApi.getMiniAppSecret()
                + "&&js_code="
                + code
                + "&grant_type=authorization_code";
        JSONObject json = Util.getResult(urls);
        accessToken = json.getString("session_key");
        String openId = json.getString("openid");
        if(openId==null){
            map.put("flag","error");
            map.put("msg","openId获取失败，需要跳转到登录页面重新获取");
            return map;
        }
//        String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
//                + accessToken + "&openid=" + openId + "&lang=zh_CN";
//        JSONObject userInfo = Util.getResult(userUrl);
        Example example = new Example(SUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openId",openId);
        SUser user = scUserMapper.selectOneByExample(example);
        if(user==null){
//            String nickname = userInfo.getString("nickname");
//            String province = userInfo.getString("province");
//            String city = userInfo.getString("city");
//            String headImg = userInfo.getString("headimgurl");
            user = new SUser();
//            user.setUserName(nickname);
            user.setCompanyId(companyId);
           user.setUserBalance(0.0);
           user.setUserScore(0);
           user.setDiamondNum(0);
           user.setOpenId(openId);
           user.setUserPassword("123456");
           user.setCreateTime(DateFormatHelper.currentTimes());
           user.setUserType(0);
           user.setParentId(parentId);
           user.setShareId(shareId);
           user.setHasZg(0);
           user.setVipLevel(0);
           user.setUsedPoints(0);
           scUserMapper.addUser(user);
        }
        map.put("user",user);
        return map;
    }

    @Override
    public List<Identity> getIdentityByCompanyId(Integer companyId) {
       Example example = new Example(Identity.class);
       Example.Criteria criteria = example.createCriteria();
       if (companyId!=null){
           criteria.andEqualTo("companyId",companyId);
       }
       return scIdentityMapper.selectByExample(example);
    }

    @Override
    public void removeIdentityMenuById(String IndentityInfoIds) {
        String[] split = IndentityInfoIds.split(",");
        Example example = new Example(IdentityInfo.class);
        example.createCriteria().andIn("identityInfoId",Arrays.asList(split));
        scIdentityinfoMapper.deleteByExample(example);
    }

    @Override
    public List<Identity> getIdentityMenuById(Integer identityId) {
        List<Identity> list =  scIdentityinfoMapper.getIdentityMenuById(identityId);
        return list;
    }

    @Override
    public List<Menu> getMenuList() {
        List<Menu> menus = scMenuMapper.selectAll();
        return menus;
    }

    @Override
    public List<ProductCompany> getCompanyList() {
        List<ProductCompany> companies = scCompanyMapper.selectAll();
        return companies;
    }

    @Override
    public PageInfo getpromoterList(String userName,Integer companyId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List <SUser> list = scUserMapper.getpromoterList(userName,companyId);
        return new PageInfo(list);
    }

    @Override
    public Map listMyUser(Integer userId, Integer flag,HttpServletRequest request) {
        map = new HashMap();
        //0邀请码 1邀请人 2我的推广会员
            SUser   user = scUserMapper.listParentOrShare(userId);
            if(user.getYqm()==null){
                Integer parentId=0;
                if(user.getUserType()==2){
                    parentId = user.getUserId();
                }else{
                    parentId =user.getParentId();
                }
                Object yqm =cenerateTheQrCode(user.getCompanyId(),user.getUserId(),parentId,request);
                user.setYqm(yqm.toString());
                scUserMapper.updateByPrimaryKeySelective(user);

            }
            map.put("yqm",user.getYqm());
            map.put("shareOrParent",user);

            List<SUser > myUsers   = scUserMapper.listMyUsers(userId);
            map.put("myUsers",myUsers);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCommission(Integer userId, Double grantMoney, String note) {
        UserCommDetail detail  = new UserCommDetail();
        detail.setDetailNote(note);
        detail.setTotalMoney(grantMoney);
        detail.setUserId(userId);
        detail.setDateTime(DateFormatHelper.currentTimes());
        detail.setDetailFlag(1);
        detailsMapper.insertSelective(detail);

        commissionMapper.updateUserCommission(grantMoney,userId);

    }

    @Override
    public List<UserCommDetail> listCommission(Integer userId) {
        Example example = new Example(UserCommDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId).andEqualTo("detailFlag",1);
        example.orderBy("detailId").desc();
        return detailsMapper.selectByExample(example);
    }

    @Override
    public void addApply(Integer userId, Integer companyId) {
        PromoterApply apply = new PromoterApply();
        apply.setApplyReason("申请成为推广员");
        apply.setApplyStatus(0);
        apply.setUserId(userId);
        apply.setCompanyId(companyId);
        apply.setCompanyOpinion(0);
        apply.setMainCompanyOpinion(0);
        apply.setCreateTime(DateFormatHelper.currentTimes());
        promoterApplyMapper.insertSelective(apply);



    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyPromoter(Integer userIds, String applyIds, Integer companyId, HttpServletRequest request) {
        for (String applyId : applyIds.split(",")) {
            PromoterApply apply = new PromoterApply();
            apply.setApplyId(Integer.parseInt(applyId));
            if(companyId==1){
                //总公司审核
                apply.setMainCompanyOpinion(1);
                apply.setHandleTimeM(DateFormatHelper.currentTimes());

            }else{
                //分公司审核
                apply.setCompanyOpinion(1);
                apply.setHandleTime(DateFormatHelper.currentTimes());
            }
            if(companyId==1){
                PromoterApply promoterApply = promoterApplyMapper.selectByPrimaryKey(apply.getApplyId());
                updateUserType(promoterApply.getUserId(),request);
            }
            promoterApplyMapper.updateByPrimaryKeySelective(apply);
        }
    }

    @Override
    public SUser updateUser(Integer userId, String userName, String userPhone, HttpServletRequest request) {
        String contentType = request.getContentType();
        String fileName = null;
        if(contentType.contains("multipart/form-data")){
            MultipartFile file = ((MultipartRequest) request).getFile("file");

            if (file != null) {
                fileName = OSSUtil.uploadingImg(file, "xiuzheng/user");
            }
        }
        SUser user =scUserMapper.selectByPrimaryKey(userId);
        user.setUserId(userId);
        user.setUserName(userName);
        user.setUserImg(fileName);
        user.setUserPhone(userPhone);
        scUserMapper.updateByPrimaryKeySelective(user);
        return user;
    }

    @Override
    public Map listMyCommission(Integer userId, Integer companyId) {
        Example example = new Example(UserCommission.class);
        Example.Criteria criteria =  example.createCriteria();
        criteria.andEqualTo("userId",userId);
        UserCommission userCommission = commissionMapper.selectOneByExample(example);
        List<UserCommDetail> details = detailsMapper.listCommission(userId);
        map = new HashMap();
        map.put("userCommission",userCommission);
        map.put("details",details);
        return map;
    }

    @Override
    public Map listMyAccount(Integer userId) {
        Example example = new Example(UserScore.class);
        Example.Criteria criteria =  example.createCriteria();
        criteria.andEqualTo("userId",userId);
        example.orderBy("scoreId").desc();
        List<UserScore> userScores = scoreMapper.selectByExample(example);
        map = new HashMap();
        map.put("userScores",userScores);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map exchangeUserType(Integer userId, String userName, String userPhone, String code) {
        Example example = new Example(PromoCode.class);
        Example.Criteria criteria =example.createCriteria();
        criteria.andEqualTo("codeContent",code);
        PromoCode codes = promoCodeMapper.selectOneByExample(example);
        map = new HashMap();
        if(codes==null){
            map.put("flag", "error");
            map.put("msg", "请输入正确的兑换码");
            return map;
        }
        if(codes.getCodeStatus()==1){
            map.put("flag", "error");
            map.put("msg", "该兑换码已被使用");
            return map;
        }
        if(!userName.equals(codes.getUserName())||!userPhone.equals(codes.getUserPhone())){
            map.put("flag", "error");
            map.put("msg", "该兑换码与您填写的信息不符合");
            return map;
        }
        SUser user = new SUser();
        user.setUserType(2);
        user.setInviteCode(codes.getCodeContent());
        scUserMapper.updateByPrimaryKeySelective(user);
        codes.setCodeStatus(1);
        promoCodeMapper.updateByPrimaryKeySelective(codes);
        map.put("flag","true");
        map.put("msg","兑换成功");


        //添加我的佣金信息
        UserCommission commission  = new UserCommission();
        commission.setUserId(user.getParentId());
        commission.setRechargeMoney(0.0);
        commission.setRechargeNum(0);
        commission.setGrantMoney(0.0);
        commission.setTotalMoney(0.0);
        commissionMapper.insertSelective(commission);
        return map;

    }

    @Override
    public void deleteAddress(Integer addressId) {
        scAddressMapper.deleteByPrimaryKey(addressId);

    }

    @Override
    public void setAddress(Integer addressId,Integer userId) {
        Example example = new Example(Address.class);
        Example.Criteria criteria =example.createCriteria();
        criteria.andEqualTo("userId",userId);
        Address address = new Address();
        address.setAddressFlag(0);
        scAddressMapper.updateByExampleSelective(address,example);
        address = new Address();
        address.setAddressId(addressId);
        address.setAddressFlag(1);
        scAddressMapper.updateByPrimaryKeySelective(address);

    }

    @Override
    public Object listMemberNum(Integer userId) {
        Example example = new Example(SUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("shareId",userId).andEqualTo("userType",1);
        return scUserMapper.selectByExample(example).size();
    }

    @Override
    public Map getMoney(Integer userId, String openId, String userName,String money) {
        map = new HashMap();

        String maps = WxTiXian.weixinTransferBat(money, openId, userName + "余额提现");
        System.out.println("用户余额提现开始");
        System.out.println(maps);
        JSONObject object = JSON.parseObject(maps);
        System.out.println(object.get("code"));
        System.out.println(object.get("batch_id"));
        System.out.println("用户余额提现结束");
        if (object.get("batch_id").equals("") || object.get("batch_id") == null) {
            map.put("flag", "error");
            map.put("datas", maps);
        } else {
            UserScore score = new UserScore();
            score.setUserId(userId);
            score.setDiamondNum(0);
            score.setCreateTime(DateFormatHelper.currentTimes());
            score.setScoreType(2);
            score.setOrderNumber("0");
            score.setUsedMoney(Double.valueOf(money));
            score.setScoreNum(0);
            score.setAcceptMoney(0);

            score.setUserId(userId);

            scoreMapper.insertSelective(score);
            scUserMapper.updateMoney(Double.valueOf(money), userId);
            map.put("flag", "success");
        }


        return map;
    }
    public void PromoterDown(Integer userId, Integer companyId, String note) {
        PromoterApply promoterApply= new PromoterApply();
        promoterApply.setUserId(userId);
        promoterApply.setCompanyId(companyId);
        promoterApply.setApplyReason(note);
        promoterApply.setApplyStatus(1);
        promoterApply.setCreateTime(DateFormatHelper.today());
        promoterApply.setMainCompanyOpinion(0);
        promoterApply.setCompanyOpinion(0);
        promoterApplyMapper.insertSelective(promoterApply);
    }


    @Override
    public void PromoterDownApply(Integer userId, String applyIds, Integer companyId) {
        for (String applyId : applyIds.split(",")) {
            if (companyId != 1) {
                //分销公司确认离职申请
                PromoterApply apply = new PromoterApply();
                apply.setApplyId(Integer.valueOf(applyId));
                apply.setCompanyOpinion(1);
                apply.setHandleTime(DateFormatHelper.today());
                promoterApplyMapper.updateByPrimaryKeySelective(apply);
                return;
            }

            //1.更改推广员状态为会员 清除绑定的二维码
            scUserMapper.updateUserTypeDown(userId);
            //2.将推广员下面所有会员所属改为主公司
            Example example = new Example(SUser.class);
            example.createCriteria().andEqualTo("parentId", userId).andEqualTo("userType", 1);
            SUser user = new SUser();
            user.setParentId(0);
            scUserMapper.updateByExampleSelective(user, example);
        /*List<SUser> sUsers = scUserMapper.selectByExample(example);
       sUsers.forEach(sUser -> {
           scUserMapper.updateUserParent(sUser.getUserId());
       });*/
            //主公司确认离职申请
            PromoterApply apply1 = new PromoterApply();
            apply1.setApplyId(Integer.valueOf(applyId));
            apply1.setMainCompanyOpinion(1);
            apply1.setHandleTimeM(DateFormatHelper.today());
            promoterApplyMapper.updateByPrimaryKeySelective(apply1);
        }
    }

    @Override
    public SUser newGetUser(Integer userId) {
        redisTemplate.delete("isUpdate_"+userId);
        return scUserMapper.selectByPrimaryKey(userId);
    }

    private void updateUserType(Integer userId,HttpServletRequest request){
            SUser user = scUserMapper.selectByPrimaryKey(userId);
            user.setUserType(2);
            //更新我的身份
            scUserMapper.updateByPrimaryKeySelective(user);
            //改变shareId==userId  并且是游客所有的推广员Id
            SUser users = new SUser();
            users.setParentId(userId);
            Example example = new Example(SUser.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("shareId", userId).andEqualTo("userType", 0);
            scUserMapper.updateByExampleSelective(users, example);

            //更新用户的推广码
            cenerateTheQrCode(user.getCompanyId(), userId, userId, request);
            //新增用户佣金账户
            UserCommission commission = new UserCommission();
            commission.setUserId(user.getParentId());
            commission.setRechargeMoney(0.0);
            commission.setRechargeNum(0);
            commission.setGrantMoney(0.0);
            commission.setTotalMoney(0.0);
            commissionMapper.insertSelective(commission);
        }


    private  Object cenerateTheQrCode(Integer companyId,Integer shareId,Integer parentId, HttpServletRequest request) {
        String picName="";
        String urls = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WxApi.getMiniAppId()+"&secret="+WxApi.getMiniAppSecret();
        JSONObject demoJson = Util.getResult(urls);
        String accessToken = demoJson.get("access_token").toString();
        //调用上面方法，获取accessToken，建议对accessToken进行缓存，
        //appid：小程序appid，appsecret：小程序密钥
        Map<String, Object> params = new HashMap<>();
        //参数,一个可以直接放入参数例如:1 多个例如：id=1&name=2&...
        params.put("scene", "companyId="+companyId+"&shareId="+shareId+"&parentId="+parentId);
        params.put("page", "pages/index/index"); //扫码后进入小程序的页面位置
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 接口
        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JSON.toJSONString(params);//必须是json模式的 post
        StringEntity entity = null;
        try {
            entity = new StringEntity(body);
            entity.setContentType("image/png");//也可以是image/jpg
            httpPost.setEntity(entity);
            HttpResponse response;
            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            picName = shareId + ".png";//文件名加后缀，跟上面对应
            String path = "D:\\nginx-1.19.1\\html\\zhibanzhang\\resource\\xiuzheng\\user\\";//图片保存路径
            Util.saveToImgByInputStream(inputStream, path, picName);  //保存图片

        } catch (Exception e) {
            e.printStackTrace();
        }
        return picName;
    }


}
